from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 定义一个K值范围
k_range = list(range(1, 31))
k_scores = []

# 对每个K值进行交叉验证
for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy')
    k_scores.append(scores.mean())

# 找到最佳的K值
best_k = k_range[k_scores.index(max(k_scores))]
print("最佳K值:", best_k)
